<style>
    .demo-spin-icon-load {
        animation: ani-demo-spin 1s linear infinite;
    }

    @keyframes ani-demo-spin {
        from {
            transform: rotate(0deg);
        }
        50% {
            transform: rotate(180deg);
        }
        to {
            transform: rotate(360deg);
        }
    }
</style>
<template>
    <div class="role">

        <div class="grid" v-show="show == 1">
            <sticky>
                <Tooltip content="新增" placement="bottom-start">
                    <Button type="info" @click="create()">创建</Button>
                </Tooltip>
                <Tooltip content="编辑" placement="bottom-start">
                    <Button type="success" @click="edit()">编辑</Button>
                </Tooltip>
                <Tooltip content="删除" placement="bottom-start">
                    <Button type="error" @click="del()">删除</Button>
                </Tooltip>
                <Tooltip content="刷新" placement="bottom-start">
                    <Button @click="query()">
                        <Icon type="refresh"></Icon>
                    </Button>
                </Tooltip>

            </sticky>

            <Card :bordered="false">

                <Table highlight-row :loading="loading" stripe border :columns="columns" :data="rows"
                       @on-current-change="handleRowChange"></Table>

                <div style="margin: 10px;overflow: hidden">
                    <div style="float: right;">
                        <Page :total="total" show-total="true" placement="top" show-sizer @on-change="goPage"></Page>
                    </div>
                </div>
            </Card>
            <Spin fix size="large" fix v-if="spinShow">
                <Icon type="load-c" class="demo-spin-icon-load" size=18></Icon>
                <div>拼命加载中...</div>
            </Spin>
        </div>
        <div class="panel" v-show="show == 2">
            <Card :bordered="false">
                <p slot="title">{{title}}</p>
                <Row>
                    <Col span="12">
                    <Form ref="formItem" :model="formItem" :rules="ruleItem" :label-width="80">
                        <FormItem maxlength="50" label="角色名称" prop="roleName" ref="roleName">
                            <Input v-model="formItem.roleName" placeholder="输入角色名称..."></Input>
                        </FormItem>
                        <FormItem label="角色编码" prop="permission" ref="permission">
                            <Input maxlength="50" v-model="formItem.permission" placeholder="输入角色编码..."></Input>
                        </FormItem>
                        <FormItem label="保留" prop="roleType">
                            <i-switch v-model="formItem.roleType" size="large" true-value="1" false-value="0">
                                <span slot="open">是</span>
                                <span slot="close">否</span>
                            </i-switch>
                        </FormItem>
                        <FormItem label="状态" prop="roleStatus">
                            <i-switch v-model="formItem.roleStatus" size="large" true-value="1" false-value="0">
                                <span slot="open">启用</span>
                                <span slot="close">禁用</span>
                            </i-switch>
                        </FormItem>
                        <FormItem label="排序" prop="order">
                            <Input type="number" v-model="formItem.order" placeholder="输入排序..."></Input>
                        </FormItem>
                        <FormItem label="备注" prop="remark">
                            <Input maxlength="1000" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                                   v-model="formItem.remark"
                                   placeholder="输入备注..."></Input>
                        </FormItem>

                        <FormItem>
                            <Button type="primary" @click="handleSubmit('formItem')">保存</Button>
                            <Button type="ghost" @click="goBack()" style="margin-left: 8px">返回</Button>
                        </FormItem>
                    </Form>
                    </Col>
                </Row>
            </Card>
        </div>
    </div>

</template>
<script>
    import Sticky from '@/components/Sticky' // 粘性header组件
    import canEditTable from '@/components/tables/canEditTable';
    import Util from '@/libs/util'
    import iView from 'iview'
    import moment from 'moment'

    var qs = require('qs');
    export default {
        components: {
            Sticky,
            canEditTable
        },
        data() {
            return {
                loading: false,
                show: 1,
                title: '创建角色',
                index: 0,
                total: 0,
                currentRow: null,
                spinShow: false,
                oldRoleName: null,
                oldPermission: null,
                columns: [
                    {
                        title: '角色名称',
                        key: 'roleName',
                        editable: true
                    },
                    {
                        title: '角色编码',
                        key: 'permission',
                        //fixed: 'left'
                    },
                    {
                        title: '当前状态',
                        key: 'roleStatus',
                        render: (h, params) => {
                            let roleStatus = params.row.roleStatus;
                            return h('div', [
                                h('Tag', {
                                    props: {
                                        color: roleStatus == 1 ? "green" : "red"
                                    },
                                    on: {
                                        "on-change": (status) => {

                                        }
                                    }
                                }, roleStatus == 1 ? "启用" : "停用"),
                            ]);
                        }
                    },
                    {
                        title: '创建人',
                        key: 'createPerson'
                    },
                    {
                        title: '创建时间',
                        key: 'createTime',
                        render: (h, params) => {
                            var createTime = params.row.createTime;
                            return createTime == null ? "" : moment(createTime).format('YYYY-MM-DD HH:mm');
                        }
                    }

                ],
                rows: [],
                formItem: {
                    roleName: '',
                    permission: '',
                    roleType: "1",
                    roleStatus: "1",
                    order: '',
                    remark: '',
                    roleId: ''
                },
                ruleItem: {
                    roleName: [
                        {
                            required: true, trigger: 'blur', validator(rule, value, callback) {
                            if (value == '') {
                                callback(new Error('角色名称不能为空.'));
                                return;
                            }

                            //没有修改则不验证
                            let roleName = sessionStorage.getItem('roleName');
                            if (roleName == value) {
                                callback();
                                return;
                            }

                            Util.axios.post('/ms/role/validateRoleName', qs.stringify({roleName: value})).then(res => {
                                if (!res.data.result)
                                    callback(new Error(res.data.msg));
                                else
                                    callback();
                            });
                        }
                        }
                    ],
                    permission: [
                        {
                            required: true,
                            trigger: 'blur',
                            message: '角色编码不能为空.'
                        },
                        {
                            max: 50,
                            message: '最大长度为50',
                            trigger: 'blur'
                        },
                        {
                            type: 'string',
                            pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
                            message: '以英文字母开头，只能包含英文字母、数字、下划线',
                            trigger: 'blur'
                        },
                        {
                            validator(rule, value, callback) {
                                if (value == '') {
                                    callback(new Error('角色编码不能为空.'));
                                    return;
                                }
                                //没有修改则不验证
                                let permission = sessionStorage.getItem('permission');
                                if (permission == value) {
                                    callback();
                                    return;
                                }
                                Util.axios.post('/ms/role/validateRolePermission', qs.stringify({permission: value})).then(res => {
                                    if (!res.data.result)
                                        callback(new Error(res.data.msg));
                                    else
                                        callback();
                                });
                            }
                        }
                    ]

                }
            }
        },
        methods: {
            /**
             * 点击创建按钮
             */
            create() {
                //重置表单
                this.$refs['formItem'].resetFields();
                this.show = 2;
            },
            // 编辑
            edit() {
                if (!this.currentRow) {
                    this.$Message.error('请选择需要操作的数据列');
                    return;
                }
                this.show = 2;
                this.formItem = this.currentRow;
                sessionStorage.setItem('roleName', this.currentRow.roleName);
                sessionStorage.setItem('permission', this.currentRow.permission);
            },
            del() {
                if (!this.currentRow) {
                    this.$Message.error('请选择需要操作的数据列');
                    return;
                }
                let me = this;
                this.$Modal.confirm({
                    title: '删除确定',
                    content: '是否继续删除?',
                    onOk: () => {
                        me.spinShow = true;
                        Util.axios.post('/ms/role/del', qs.stringify({id: me.currentRow.roleId})).then(res => {
                            me.spinShow = false;
                            if (res.data.result) {
                                this.$Modal.remove();
                                me.query();
                            }
                            else
                                this.$Message.success(res.data.msg);
                        });

                    },
                    onCancel: () => {
                        this.$Message.info('操作取消');
                    }
                });

            },
            handleRowChange(currentRow, oldCurrentRow) {
                this.currentRow = currentRow;
            },
            handleSubmit(name) {
                let me = this;
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        let form = me.formItem;
                        me.spinShow = true;
                        Util.axios.post(form.roleId == '' ? '/ms/role/save' : '/ms/role/update', form).then(res => {
                            me.spinShow = false;
                            if (res.data.result) {
                                me.query();
                                me.show = 1;
                            }
                            this.$Message.success(res.data.msg);
                        });
                    } else {
                        this.$Message.error('Fail!');
                    }
                })
            },
            handleCellChange(val, index, key) {
                let me = this;
                let roleName = val[index][key];
                if (roleName.length > 50) {
                    me.$Message.success('最大长度为50');
                    return;
                }
                me.update(roleName, val[index].roleStatus, val[index].roleId);
            },
            update(roleName, roleStatus, roleId) {

                let me = this;
                Util.axios.post('/ms/role/update', qs.stringify({
                    roleName: roleName,
                    roleStatus: roleStatus,
                    roleId: roleId
                })).then(res => {
                    me.spinShow = false;
                    if (res.data.result) {
                        me.query();
                    }
                    me.$Message.success(res.data.msg);
                });
            },
            goBack() {
                this.show = 1;
            },
            /**
             * 查询列表
             */
            query() {
                var me = this;
                me.loading = true;
                let page = {'size': 10, 'page': this.index};
                Util.axios.post('/ms/role/query', qs.stringify(page)).then(res => {
                    var data = res.data;
                    if (data.result) {
                        me.total = data.data.total;
                        me.rows = data.data.rows;
                    }
                    me.loading = false;
                });
            },
            /**
             * 翻页
             * @param index
             */
            goPage(index) {
                this.index = index - 1;
                this.query();
            },
        },
        created() {
            this.query();
        }
    }
</script>
